package com.sdx.console.content.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.DictBusiness;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.common.entity.BaseProvince;
import com.sdx.console.common.service.BaseDataService;
import com.sdx.console.content.entity.ResColumn;
import com.sdx.console.content.entity.ResContentColumn;
import com.sdx.console.content.entity.ResContentMain;
import com.sdx.console.content.entity.ResTag;
import com.sdx.console.content.service.ResColumnService;
import com.sdx.console.content.service.ResContentColumnService;
import com.sdx.console.content.service.ResContentMainService;
import com.sdx.console.content.service.ResTagService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.console.system.service.DictBusinessService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ResContentMain 接口
 */
@RequestMapping("/content/resContentMain")
@Controller
public class ResContentMainController extends AuthorizedBaesController {
	private static final Logger log = LoggerFactory.getLogger(ResContentMainController.class);
	private static final String MODEL = "/content/resContentMain";


	@Resource
	private ResContentMainService resContentMainService;

	@Resource
	private ResTagService resTagService;

	@Resource
	private DictBusinessService dictBusinessService;

	@Resource
	private BaseDataService baseDataService;

	@Resource
	private ResColumnService resColumnService;

	@Resource
	private ResCloudFileService resCloudFileService;

	@Autowired
	private ResContentColumnService resContentColumnService;

	@Resource
	private CustomerInfoService customerInfoService;

	@Resource
	private CorePlatformService corePlatformService;

	/* 页面 */

	@GetMapping("/index.do")
	@Function("content.resContentMain.query,content.resContentMain.query1")
	@ResponseBody
	public ModelAndView index(int mediaType,HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MODEL + "/index.html");
		view.addObject("mediaType", mediaType);
		initEditPage(view,request);
		return view;
	}

	/**
	 * 初始化编辑页面
	 *
	 * @param view
	 */
	private void initEditPage(ModelAndView view,HttpServletRequest request) {
		Integer accessType = corePlatformService.getAccessType(request);
		List<ResTag> list = resTagService.getValidList();
		view.addObject("resTagList", JSON.toJSONString(list));
		view.addObject("resTag", list);
		List<DictBusiness> moduleList = dictBusinessService.getModule();
		view.addObject("moduleList",moduleList);
		view.addObject("provinceList",baseDataService.getAllProvince());
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setIsTeacher(1);
		List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
		Integer provinceId =null;
		if (accessType.intValue()<6) {
			CoreOrg currentOrg = corePlatformService.getCurrentOrg();
			provinceId = currentOrg.getProvinceId();
		}
		view.addObject("customerInfoList",customerInfoList);
		view.addObject("accessType",accessType);
		view.addObject("provinceId",provinceId);
	}

	@GetMapping("/edit.do")
	@Function("content.resContentMain.edit,content.resContentMain.edit1")
	@ResponseBody
	public ModelAndView edit(Integer contentId,HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MODEL + "/add.html");
		ResContentMain resContentMain = resContentMainService.queryById(contentId);
		if (StringUtils.isNotEmpty(resContentMain.getContentTags())) {
			String contentTags = "'" + resContentMain.getContentTags().replaceAll(",", "','") + "'";
			view.addObject("selectedTags", contentTags);
		}
		view.addObject("resContentMain", resContentMain);
		initEditPage(view,request);
		Integer accessType = corePlatformService.getAccessType(request);
		if (accessType.intValue()<6) {
			BaseProvince province = baseDataService.getProvince(resContentMain.getProvinceId());
			view.addObject("provinceId",resContentMain.getProvinceId());
			view.addObject("provinceName",province.getProvName());
		}
		if(resContentMain.getContentType()!=null){
			resContentMain.setContentType("'"+resContentMain.getContentType().replaceAll(",","','")+"'");
		}
		view.addObject("mediaType", resContentMain.getMediaType());
		try {
			view.addObject("resContentMainJson", JacksonUtils.toJsonString(resContentMain, JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return view;
	}

	@GetMapping("/add.do")
	@Function("content.resContentMain.add,content.resContentMain.add1")
	@ResponseBody
	public ModelAndView add(int mediaType,HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MODEL + "/add.html");
		view.addObject("mediaType", mediaType);
		initEditPage(view,request);
		Integer accessType = corePlatformService.getAccessType(request);
		if (accessType.intValue()<6) {
			CoreOrg org = corePlatformService.getCurrentOrg();
			BaseProvince province = baseDataService.getProvince(org.getProvinceId());
			view.addObject("provinceName",province.getProvName());
			view.addObject("provinceId",org.getProvinceId());
		}
		return view;
	}


	/* ajax json */

	@PostMapping("/getColumns.json")
	@Function("content.resContentMain.query,content.resContentMain.query1")
	@ResponseBody
	public List<ResColumn> getColumns(String moduleId,Integer provinceId) {
		ResColumn param = new ResColumn();
		param.setModule(moduleId);
		param.setProvId(provinceId);
//		List<ResColumn> resColumnList = resColumnService.template(param,"col_id asc");
		List<ResColumn> resColumnList =  resColumnService.queryColumnList(moduleId,String.valueOf(provinceId));
		resColumnList = resColumnList.stream().filter(a -> !a.getColName().equals("我的关注")).collect(Collectors.toList());
        return resColumnList;
	}

	@PostMapping("/list.json")
	@Function("content.resContentMain.query,content.resContentMain.query1")
	@ResponseBody
	public JsonResult<PageQuery> list(ResContentMain condtion,HttpServletRequest request) {
		PageQuery page = condtion.getPageQuery();
		Integer accessType = corePlatformService.getAccessType(request);
		if (accessType.intValue()==1) {
			condtion.setCreatedBy(getLoginUser(request).getId().intValue());
		} else if (accessType.intValue()==3) {
			CoreOrg currentOrg = corePlatformService.getCurrentOrg();
			condtion.setProvinceId(currentOrg.getProvinceId());
		}
		resContentMainService.queryByCondition(page);
		return JsonResult.success(page);
	}

	private JsonResult save(boolean isNew, ResContentMain resContentMain, HttpServletRequest request
			, MultipartFile coverFile
	) {
		JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
		String subPath = "/image/information/" + dir + "/";
		String bucketName = "sdxcomm";
		if (!FileUtils.isEmptyFile(coverFile)) {
			try {
				String fileNamePair = FileUtils.upload(subPath, coverFile);
				String storeFile = fileNamePair.split("::")[0];
				storeFile = subPath + storeFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
				String workPicurlUrl = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
				resContentMain.setCover(workPicurlUrl);
				resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,workPicurlUrl,"a","内容封面");
			} catch (Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
		CoreUser user = getLoginUser(request);

		if (isNew) {
			resContentMain.setCreatedBy(user.getId().intValue());
			resContentMain.setCreatedName(user.getName());
			resContentMain.setCreatedTime(new Date());
			resContentMain.setUpdatedBy(user.getId().intValue());
			resContentMain.setUpdatedName(user.getName());
			resContentMain.setUpdatedTime(new Date());
			Integer accessType = corePlatformService.getAccessType(request);
			if (accessType.intValue()<6) {
				CoreOrg currentOrg = corePlatformService.getCurrentOrg();
				resContentMain.setProvinceId(currentOrg.getProvinceId());
			}
			//新增，初始化字段值
			resContentMain.setContentStatus(0);
			resContentMain.setChapterNum(0);
			resContentMain.setOrderCount(0);
			resContentMain.setViewCount(0);

			if(StringUtils.isNotEmpty(resContentMain.getAuthor())){

			}
			resContentMainService.save(resContentMain);

			//插入关联表 res_content_column
//			String[] content_type = resContentMain.getContentType().split(",");
//			List resContentColumnList = new ArrayList();
//			for (String type_id: content_type) {
//				int colId = Integer.valueOf(type_id);
//				ResContentColumn resContentColumn1 = new ResContentColumn(colId,resContentMain.getContentId());
//				resContentColumnList.add(resContentColumn1);
//			}
//			this.resContentColumnService.insertBatch(ResContentColumn.class, resContentColumnList);

		} else {
			resContentMain.setUpdatedBy(user.getId().intValue());
			resContentMain.setUpdatedName(user.getName());
			resContentMain.setUpdatedTime(new Date());
			resContentMainService.updateTemplate(resContentMain);

//			//1. 先根据内容ID删除关联表记录 res_content_column
//			String[] contentId = {String.valueOf(resContentMain.getContentId())};
//			resContentColumnService.batchDelResContentColumnBycontentIds(Arrays.asList(contentId));
//			//2. 再插入关联表 res_content_column
//			String[] content_type = resContentMain.getContentType().split(",");
//			List resContentColumnList = new ArrayList();
//			for (String type_id: content_type) {
//				int colId = Integer.valueOf(type_id);
//				ResContentColumn resContentColumn1 = new ResContentColumn(colId,resContentMain.getContentId());
//				resContentColumnList.add(resContentColumn1);
//			}
//			this.resContentColumnService.insertBatch(ResContentColumn.class, resContentColumnList);
		}
		return result;
	}

	@PostMapping("/add.json")
	@Function("content.resContentMain.add,content.resContentMain.add1")
	@ResponseBody
	public JsonResult add(@Validated(ValidateConfig.ADD.class) ResContentMain resContentMain, HttpServletRequest request
			, @RequestParam("coverFile") MultipartFile coverFile
	) {
		return save(true, resContentMain, request, coverFile);
	}

	@PostMapping("/update.json")
	@Function("content.resContentMain.edit,content.resContentMain.edit1")
	@ResponseBody
	public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class) ResContentMain resContentMain, HttpServletRequest request
			, @RequestParam("coverFile") MultipartFile coverFile
	) {
		return save(false, resContentMain, request
				, coverFile
		);
	}


	@GetMapping("/view.json")
	@Function("content.resContentMain.query,content.resContentMain.query1")
	@ResponseBody
	public JsonResult<ResContentMain> queryInfo(Integer contentId) {
		ResContentMain resContentMain = resContentMainService.queryById(contentId);
		return JsonResult.success(resContentMain);
	}

	@PostMapping("/delete.json")
	@Function("content.resContentMain.delete,content.resContentMain.delete1")
	@ResponseBody
	public JsonResult delete(String ids) {
		if (ids.endsWith(",")) {
			ids = StringUtils.substringBeforeLast(ids, ",");
		}
		//List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList, ids.split(","));
		resContentMainService.batchDelResContentMain(idList);

		//删除关联表记录
		resContentColumnService.batchDelResContentColumnBycontentIds(idList);

		return JsonResult.success();
	}

	/**
	 * 改变状态的操作，比如上线，和下线
	 *
	 * @param id
	 * @param contentStatus
	 * @return
	 */
	@PostMapping("/status.json")
	@Function("content.resContentMain.status,content.resContentMain.status1")
	@ResponseBody
	public JsonResult status(Integer id, Integer contentStatus,HttpServletRequest request) {
		CoreUser user = getLoginUser(request);
		ResContentMain contentMain = resContentMainService.queryById(id);
		if (contentMain == null) {
			return JsonResult.failMessage("内容不存在。");
		}
		if (contentStatus.intValue() != contentMain.getContentStatus().intValue()) {
			return JsonResult.failMessage("数据异常，内容状态之前已经改变。");
		}
		//0新建，1，上线，-1，下线
		ResContentMain param = new ResContentMain();
		param.setContentId(id);
		if (contentStatus == 0 || contentStatus == -1) {
			//内容上线
			/**
			if (contentMain.getChapterNum() <= 0) {
				return JsonResult.failMessage("章节数为0，不能上线。");
			}
			 */
			param.setContentStatus(1);
		} else {
			param.setContentStatus(-1);
		}
		param.setUpdatedBy(user.getId().intValue());
		param.setUpdatedName(user.getName());
		param.setUpdatedTime(new Date());
		resContentMainService.updateTemplate(param);
		return JsonResult.success();
	}


	@PostMapping("/recommend.json")
	@Function("content.resContentMain.status,content.resContentMain.status1")
	@ResponseBody
	public JsonResult recommend(Integer id, Integer isRecommend,HttpServletRequest request) {
		CoreUser user = getLoginUser(request);
		ResContentMain contentMain = resContentMainService.queryById(id);
		if (contentMain == null) {
			return JsonResult.failMessage("内容不存在。");
		}
		if (isRecommend.intValue() != contentMain.getIsRecommend().intValue()) {
			return JsonResult.failMessage("数据异常，内容状态之前已经改变。");
		}
		//0 不推荐，1，推荐
		ResContentMain param = new ResContentMain();
		param.setContentId(id);
		if (isRecommend == 1) {
			param.setIsRecommend(0);
		} else {
			param.setIsRecommend(1);
		}
		param.setUpdatedBy(user.getId().intValue());
		param.setUpdatedName(user.getName());
		param.setUpdatedTime(new Date());
		resContentMainService.updateTemplate(param);
		return JsonResult.success();
	}

    /**
     *  图片上传
     * @param upfile
     * @return
     */
    @RequestMapping("/upload.json")
    @ResponseBody
    public JSONObject uploadImg(MultipartFile upfile) {
        JSONObject jsobject = new JSONObject();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/information/"+dir+"/";
        String bucketName = "sdxcomm";
        if (!FileUtils.isEmptyFile(upfile)) {
            try
            {
                String fileNamePair = FileUtils.upload(subPath,upfile);
                String storeFile = fileNamePair.split("::")[0];
                storeFile = subPath+storeFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
                String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
                jsobject.put("url",url);
                jsobject.put("state", "SUCCESS");
                jsobject.put("title", "");
                jsobject.put("original", "");
                resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,url,"a","学校logo");
            }catch(Exception e) {
                e.printStackTrace();
                jsobject.put("state", "FAIL");
                jsobject.put("title", "");
                jsobject.put("original", "");
                jsobject.put("url","");
            }
        }
        return jsobject;
    }

    /**
     * 返回 ueditor 图片上传的配置参数
     * @return
     */
    @RequestMapping("/config")
    @ResponseBody
    public String config(){
        String UEDITOR_CONFIG = "{\n" +
                "    \"imageActionName\": \"uploadimage\",\n" +
                "    \"imageFieldName\": \"upfile\",\n" +
                "    \"imageMaxSize\": 2048000,\n" +
                "    \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "    \"imageCompressEnable\": true,\n" +
                "    \"imageCompressBorder\": 1600,\n" +
                "    \"imageInsertAlign\": \"none\",\n" +
                "    \"imageUrlPrefix\": \"\",\n" +
                "    \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "\n" +
                "    \"scrawlActionName\": \"uploadscrawl\",\n" +
                "    \"scrawlFieldName\": \"upfile\",\n" +
                "    \"scrawlPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"scrawlMaxSize\": 2048000,\n" +
                "    \"scrawlUrlPrefix\": \"\",\n" +
                "    \"scrawlInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"snapscreenActionName\": \"uploadimage\",\n" +
                "    \"snapscreenPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"snapscreenUrlPrefix\": \"\",\n" +
                "    \"snapscreenInsertAlign\": \"none\",\n" +
                "\n" +
                "    \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
                "    \"catcherActionName\": \"catchimage\",\n" +
                "    \"catcherFieldName\": \"source\",\n" +
                "    \"catcherPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"catcherUrlPrefix\": \"\",\n" +
                "    \"catcherMaxSize\": 2048000,\n" +
                "    \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"videoActionName\": \"uploadvideo\",\n" +
                "    \"videoFieldName\": \"upfile\",\n" +
                "    \"videoPathFormat\": \"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"videoUrlPrefix\": \"\",\n" +
                "    \"videoMaxSize\": 102400000,\n" +
                "    \"videoAllowFiles\": [\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"],\n" +
                "\n" +
                "    \"fileActionName\": \"uploadfile\",\n" +
                "    \"fileFieldName\": \"upfile\",\n" +
                "    \"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
                "    \"fileUrlPrefix\": \"\",\n" +
                "    \"fileMaxSize\": 51200000,\n" +
                "    \"fileAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ],\n" +
                "\n" +
                "    \"imageManagerActionName\": \"listimage\",\n" +
                "    \"imageManagerListPath\": \"/ueditor/jsp/upload/image/\",\n" +
                "    \"imageManagerListSize\": 20,\n" +
                "    \"imageManagerUrlPrefix\": \"\",\n" +
                "    \"imageManagerInsertAlign\": \"none\",\n" +
                "    \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
                "\n" +
                "    \"fileManagerActionName\": \"listfile\",\n" +
                "    \"fileManagerListPath\": \"/ueditor/jsp/upload/file/\",\n" +
                "    \"fileManagerUrlPrefix\": \"\",\n" +
                "    \"fileManagerListSize\": 20,\n" +
                "    \"fileManagerAllowFiles\": [\n" +
                "        \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
                "        \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
                "        \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
                "        \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
                "        \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
                "    ] \n" +
                "\n" +
                "}";
        return UEDITOR_CONFIG;
    }


	@RequestMapping("/getAuthor.json")
	@ResponseBody
	public JsonResult getAuthor(HttpServletRequest request,Integer provinceId) {
		List<BaseEntity> list = new ArrayList<>();
		if(provinceId!=null && provinceId ==0){
			provinceId = null;
		}
		list = resContentMainService.selectAuthor(provinceId);
		return JsonResult.success(list);
	}


}
